<template>
	<view>
		<u-upload 
		:action="action" 
		:max-size="5 * 1024 * 1024" 
		max-count="1"
		:multiple="false"
		:before-upload="beforeUpload"
		:custom-btn="true"
		:show-progress="false"
		:form-data="formData"
		:show-upload-list="false"
		:deletable="false"
		@on-success="onSuccess"
		>
		<!-- <u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar> -->
			<view class="u-m-l-20 u-type-warning"  slot="addBtn">修改头像</view>
		</u-upload>
	</view>
</template>

<script>
	let _this = {}
	export default {
		name:"oss-upload",
		data() {
			return {
				action: '',
				formData:{},
				upFileName: '',
			};
		},
		created() {
			_this = this
		},
		methods:{
			//文件上传前的钩子
			async beforeUpload(index, list) {
				console.log(list)
				//拿到文件名 fileName  
				const {file} = list[0]
				// #ifdef H5
				const fileName = file.name
				// #endif
				
				// #ifndef H5
				const fileName = file.path
				// #endif
				
				//请求api 得到oss token
				const ossToken = await _this.$u.api.authOssToken()
				
				console.log(ossToken.host)
				//设置上传域名
				_this.action = ossToken.host
				
				//处理唯一文件名
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				const upFileName = _this.$u.guid(20) + suffix
				console.log(upFileName)
				_this.upFileName = upFileName
				//formdata参数
				_this.formData = {
					'key': upFileName, //上传文件名
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid, 
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					'signature': ossToken.signature,
				}
				await this.$u.api.userAvatar({avatar:upFileName}) //必放这里，如果放onSuccessAPP请求提示要网址
				return true;
			},
			//上传成功之后onSuccess
			async onSuccess(){
				//请求AIP
				
				//更新缓存用户信息
				this.$u.utils.updateUser()
				
				this.$u.toast('头像更改成功')
			}
		}
	}
</script>

<style>

</style>
